import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

import importToCDN from 'vite-plugin-cdn-import'

// https://vitejs.dev/config/
export default defineConfig((mode) => {
  const env = loadEnv(mode.mode, process.cwd())
  // 使用 cdn
  let CDN
  if (env.VITE_APP_CDN === 'true') {
    CDN = importToCDN({
      modules: [
        // vue
        {
          name: 'vue',
          var: 'Vue',
          path: 'https://npm.elemecdn.com/vue@3.3.4/dist/vue.global.prod.js'
        },

        // // vue-router
        // {
        //   name: 'vue-router',
        //   var: 'VueRouter',
        //   path: 'https://npm.elemecdn.com/vue-router@4.1.6/dist/vue-router.global.prod.js'
        // },
        // axios
        {
          name: 'axios',
          var: 'axios',
          path: 'https://npm.elemecdn.com/axios@1.4.0/dist/axios.min.js'
        },
        {
          name: 'highlight.js',
          var: 'hljs',
          path: 'https://lib.baomitu.com/highlight.js/11.7.0/highlight.min.js'
        },
        // clipboard
        {
          name: 'clipboard',
          var: 'ClipboardJS',
          path: 'https://npm.elemecdn.com/clipboard@2.0.11/dist/clipboard.min.js'
        }
      ]
    })
  }

  return {
    plugins: [vue(), CDN],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },

    build: {
      // 打包目录
      outDir: './dist',

      // 静态文件管理,assetsDir和rollupOptions二选一
      // assetsDir:"assets",
      rollupOptions: {
        output: {
          // 最小化拆分包
          // manualChunks: (id) => {
          //   if (id.includes('node_modules')) {
          //     return id.toString().split('node_modules/')[1].split('/')[0].toString()
          //   }
          // },
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
        }
      },

      // 移除log
      minify: 'terser',
      terserOptions: {
        compress: {
          //生产环境时移除console.log()
          drop_console: true,
          //生产环境时移除debugger
          drop_debugger: false
        }
      }
    }
  }
})
